package com.practice.J2E.thread;

/**
 * 酸奶店顾客
 * @author kayn
 * @create 2023-09-21 下午 04:32
 */
public class YogurtBuyer implements Runnable{

    private final String name;

    private final Shop shop;

    public YogurtBuyer(String name, Shop shop) {
        this.name = name;
        this.shop = shop;
    }

    @Override
    public void run() {

        try {
            buyYogurt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void buyYogurt() throws InterruptedException {

        synchronized (shop) {

            while (shop.getYogurtList().isEmpty() && shop.getShopStatus()) {

                System.out.println(name + "来到店里发现还没有酸奶，开始抢酸奶");

                shop.wait();

            }

            if (!shop.getYogurtList().isEmpty()) {

                shop.SellYogurt(name);

                return;
            }

            System.out.println(name + "最终没抢到酸奶，猝死了");

            shop.notifyAll();

        }

    }

}
